import axios from "axios";
import { Message } from "element-ui";
import store from "@/store";
import router from "@/router";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: '/prod-api', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.token) {
      config.headers.authorization = getToken();
    }
    return config;
  },
  (config) => {
    // do something with request error
    console.log(config); // for debug
    return Promise.reject(config);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    console.log("接口返回数据res", response);

    if (response.status === 200) {
      return response;
    } else if (response.status === 401) {
      Message.error('token过期，重新登录')
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message({
        message: response.data.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
    }
    // return Promise.reject(new Error(response.data.message || 'Error'))
  },
  error => {
    console.log('err' + error) // for debug
    if (error.status === 401) {
      Message.error('token过期，重新登录')
      store.dispatch('user/logout')
      router.push('login')
    }

    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(console.log('lll'))
  }
  // response => {
  //   console.log('err' + response) // for debug
  //   if (response.status === 401) {
  //     Message.error('token过期，重新登录')
  //     store.dispatch('user/logout')
  //     router.push('login')
  //   }

  //   Message({
  //     message: response.message,
  //     type: 'error',
  //     duration: 5 * 1000
  //   })
  //   return Promise.reject(console.log('lll'))
  // }
);

export default service;
